package com.juneng.utils.wxpay;

import cn.hutool.core.io.resource.ClassPathResource;
import com.github.wxpay.sdk.WXPayConfig;
import com.juneng.utils.wechat.WeChatConfig;
import lombok.Data;
import org.springframework.util.ResourceUtils;

import java.io.*;

@Data
public class WxPayAppConfigutil  implements WXPayConfig {
     //线上
   // public static String certPath = "/home/apiclient_cert.p12";  //服务器上的路径（项目包同目录下）
    //线上
    public static String certPath = "/var/java/8082/text/apiclient_cert.p12"; //服务器上的路径（项目包同目录下）

   // public static String certPath1 = "8082/text/apiclient_cert.p12"; //服务器上的路径（项目包同目录下）
    //线下
   //  public static String certPath = "apiclient_cert.p12";
    //证书数据
    private static byte[] certData;

    //var/java/8082/text/apiclient_cert.p12
    //私有化构造器
    public WxPayAppConfigutil(){
        try{
           // ClassPathResource cp = new ClassPathResource("apiclient_cert.p12");
          //  File file = cp.getFile();
            File file = ResourceUtils.getFile(certPath);
            InputStream certStream = new FileInputStream(file);
            this.certData = new byte[(int) file.length()];
            certStream.read(this.certData);
        } catch ( IOException e ){
            e.printStackTrace();
        }
    }

    //单例对象
    private volatile static WxPayAppConfigutil singleton;

    //获取单例方法 双检锁模式
    public static WxPayAppConfigutil getInstance() {
        if (singleton == null) {
            synchronized (WxPayAppConfigutil.class) {
                if (singleton == null) {
                    singleton = new WxPayAppConfigutil();
                }
            }
        }
        return singleton;
    }

    @Override
    public String getAppID() {
        return WeChatConfig.APP_ID;
    }

    @Override
    public String getMchID() {
        return WeChatConfig.MCH_ID;
    }

    @Override
    public String getKey() {
        return WeChatConfig.APP_KEY;
    }

    @Override
    public InputStream getCertStream() {
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

    @Override
    public int getHttpConnectTimeoutMs() {
        return 8000;
    }

    @Override
    public int getHttpReadTimeoutMs() {
        return 10000;
    }

    public static void main(String[] args) {
   //cn.hutool.core.io.resource.NoResourceException: Resource of path [apiclient_cert.p12] not exist!
        try {
            byte[] certData;
            File file = ResourceUtils.getFile(certPath);
            InputStream certStream = new FileInputStream(file);
            certData = new byte[(int) file.length()];
            certStream.read(certData);
            System.out.println(certData);

          //  ClassPathResource cl = new ClassPathResource("apiclient_cert.p12");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
